package cn.brilliantfuture.commentry.refund.impl;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.jboss.wsf.spi.annotation.WebContext;

import cn.brilliantfuture.commentry.entity.OrderInformation;
import cn.brilliantfuture.commentry.entity.PickRecords;
import cn.brilliantfuture.commentry.entity.RefundDeliveryRecords;
import cn.brilliantfuture.commentry.entity.RefundOrderInfo;
import cn.brilliantfuture.commentry.entity.RefundPickRecords;
import cn.brilliantfuture.commentry.entity.StorageGrid;
import cn.brilliantfuture.commentry.entity.StorageGridPurchaserNews;
import cn.brilliantfuture.commentry.refund.RefundDeliveryMessageRemote;
import cn.brilliantfuture.commentry.refund.RefundDeliveryMessageWebService;
import cn.brilliantfuture.commentry.util.DateTimeHelper;

/**
 * 
 * Title: Communication Entry
 * 
 * Author: LiTian
 * 
 * Date: 2011-10-25
 * 
 * Description: 退货送货管理
 * 
 */
@Stateless
@WebService(endpointInterface = "cn.brilliantfuture.commentry.refund.RefundDeliveryMessageWebService")
@WebContext(contextRoot = "/commentry", urlPattern = "/RefundDeliveryMessageWebService")
public class RefundDeliveryMessageImpl implements RefundDeliveryMessageRemote,
		RefundDeliveryMessageWebService {
	protected static final Logger logger = Logger.getLogger(RefundDeliveryMessageImpl.class); 

	@PersistenceContext(unitName = "commentry-jpa")
	private EntityManager entityManager;

	@SuppressWarnings("unchecked")
	public boolean refundDeliveryWorkflow(String deviceSn, int gridNo, String rfidSn, String timestamp) {
		logger.info("RefundDeliveryMessageImpl.refundDeliveryWorkflow(String deviceSn, int gridNo, String rfidSn, String timestamp) ...");
		logger.info("deviceSN -> " + deviceSn + " gridId -> " + gridNo + " rfidSn -> " + rfidSn + " timestamp -> " + timestamp);
		StorageGridPurchaserNews sgpn = null;
		Date currentDate = new Date();
		
		//察看配送仓是否可用
		Query query  = entityManager.createQuery("select sgpn from StorageGridPurchaserNews sgpn where sgpn.closing = 0 and sgpn.storageGrid.gridNum = :gridNum and sgpn.deviceSn = :deviceSn");
		List<StorageGridPurchaserNews> sgpns = query.setParameter("gridNum", gridNo).setParameter("deviceSn", deviceSn).getResultList();
		
		//修改历史数据并察看当前货号是否已经存在
		for (StorageGridPurchaserNews temp : sgpns){
			logger.info("Current storage grid used! orderInfoNum -> " + temp.getOrderInformationNumber());
			
			if (temp.getRfidSn().equals(rfidSn) && temp.getRefund().intValue() == 1) {
				return true;
			}
			
			if (temp.getRfidSn().equals(rfidSn)) {
				sgpn = temp;
			} else {
				temp.setTakeawayTime(currentDate);
				temp.setClosing(1);
				temp.setPick(1);
				entityManager.merge(temp);
				
				//插入取货记录
				if (temp.getRefund() == 0){
					PickRecords pickRecords = new PickRecords();
					pickRecords.setCardNumber(temp.getCardNumber());
					pickRecords.setFlag(true);
					pickRecords.setInsertTime(DateTimeHelper.dateTimeToStr(currentDate, DateTimeHelper.DEFAULT_DATE_TIME_FORMAT));
					pickRecords.setOrderInformationNumber(temp.getOrderInformationNumber());
					pickRecords.setRfidSn(temp.getRfidSn());
					pickRecords.setGridNum(gridNo);
					entityManager.persist(pickRecords);
					
					//修改配送单状态
					entityManager.createNativeQuery("update order_information set transactions = 5 where number = :orderNumber").setParameter("orderNumber", temp.getOrderInformationNumber()).executeUpdate();
				} else if (temp.getRefund() == 1){
					RefundPickRecords refundPickRecords = new RefundPickRecords();
					refundPickRecords.setCardNumber(temp.getCardNumber());
					refundPickRecords.setFlag(true);
					refundPickRecords.setPickTime(currentDate);
					refundPickRecords.setOrderInfoNumber(temp.getOrderInformationNumber());
					refundPickRecords.setRfidSn(temp.getRfidSn());
					refundPickRecords.setGridNumber(gridNo);
					entityManager.persist(refundPickRecords);
					
					//修改配送单状态
					entityManager.createNativeQuery("update refund_order_info set transactions = 3 where order_info_number = :orderNumber").setParameter("orderNumber", temp.getOrderInformationNumber()).executeUpdate();
				}

				entityManager.flush();
			}
		}
		
		List<OrderInformation> orderInfos = entityManager.createQuery("select oi from OrderInformation oi inner join oi.productBatchs pb where pb.rfidSn = :rfidSn").setParameter("rfidSn", rfidSn).getResultList();
		StorageGrid storageGrid = null;
		if (orderInfos.size() != 1)
			return false;
		
		OrderInformation orderInfo = orderInfos.get(0);
		
		for (StorageGrid sg : orderInfo.getLockers().getStorageGrids())
			if (sg.getGridNum() == gridNo){
				storageGrid = sg;
				break;
			}
				
		if (null == sgpn){
			//组织配送信息
			sgpn = new StorageGridPurchaserNews();
			sgpn.setStorageGrid(storageGrid);
			sgpn.setCardNumber(orderInfo.getPurchaser().getCardInfo().getCardNumber());
			sgpn.setDelivery(1);
			sgpn.setClosing(0);
			sgpn.setPurchaser(orderInfo.getPurchaser());
			sgpn.setArrivalTime(currentDate);
			sgpn.setRfidSn(rfidSn);
			sgpn.setPick(0);
			sgpn.setLockersId(orderInfo.getLockers().getLockersId());
			sgpn.setLocationId(orderInfo.getLockers().getLocation().getLocationId());
			sgpn.setOrderInformationNumber(orderInfo.getNumber());
			sgpn.setGroupId(orderInfo.getGroup().getGroupId());
			sgpn.setDeviceSn(deviceSn);
			sgpn.setRefund(1);
			entityManager.persist(sgpn);
			
			//组织推送送记录信息
			RefundDeliveryRecords refundDeliveryRecords = new RefundDeliveryRecords();
			refundDeliveryRecords.setCardNumber(orderInfo.getPurchaser().getCardInfo().getCardNumber());
			refundDeliveryRecords.setRfidSn(rfidSn);
			refundDeliveryRecords.setGridNumber(gridNo);
			refundDeliveryRecords.setDeliveryTime(currentDate);
			refundDeliveryRecords.setLocation(orderInfo.getLockers().getLocation().getVilliage().getName() + 
					orderInfo.getLockers().getLocation().getName() + orderInfo.getLockers().getLockersName());
			refundDeliveryRecords.setPurchaserName(orderInfo.getPurchaser().getName());
			entityManager.persist(refundDeliveryRecords);
			
			entityManager.flush();
		}
		
		Object done = entityManager.createQuery("select count(sgpn) from StorageGridPurchaserNews sgpn where sgpn.refund = 1 and sgpn.orderInformationNumber = :number").setParameter("number", orderInfo.getNumber()).getSingleResult();
		
		//判断当前配送单商品是否全部退送货完成
		if (orderInfo.getProductBatchs().size() == Integer.parseInt(done.toString())){
			logger.info("All products refund delivery done ... ");
			//创建退货单信息
			RefundOrderInfo refundOrderInfo = new RefundOrderInfo();
			refundOrderInfo.setOrderInfoNumber(orderInfo.getNumber());
			refundOrderInfo.setOrderInformation(orderInfo);
			refundOrderInfo.setDeleted(false);
			refundOrderInfo.setDeliveryTime(currentDate);
			refundOrderInfo.setLockers(orderInfo.getLockers());
			refundOrderInfo.setTransactions(1);
			refundOrderInfo.setUserGroup(orderInfo.getGroup());
			entityManager.persist(refundOrderInfo);
			entityManager.flush();
		}

		return true;
	}

}
